import React from 'react';
import SwaggerEditor from 'swagger-editor';
import { connect } from 'dva';
import 'swagger-editor/dist/swagger-editor.css';
import styles from './style.less';
import { Button, message } from 'antd';

@connect(({ swaggerConfig, loading }) => ({
  swaggerConfig,
  loading: loading.models.swaggerConfig,
}))
class SwaggerEditorPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = { loaded: false };
    }

  componentDidMount() {
    window.editor = this.editor = SwaggerEditor({ dom_id: "#swagger-editor" });

    // get spec:
    // this.editor.specSelectors.specStr()

    // set spec:
    // this.editor.specActions.updateSpec('')

    const { dispatch } = this.props;
    dispatch({
      type: 'swaggerConfig/fetch',
      payload: {},
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
        const oldConfig = this.props.swaggerConfig.config;
        const newConfig = nextProps.swaggerConfig.config;

        const { loaded } = nextState;

        try {
            if ( !loaded || newConfig != oldConfig) {
                this.editor.specActions.updateSpec(newConfig);
                this.setState({ loaded: true });
            }
        } catch (error) {
            console.error(error);
        }

        // 我们自己处理后，就不用麻烦 react render 了
        return false;
  }

  reset() {
    const { swaggerConfig: { config } } = this.props;
    this.editor && this.editor.specActions.updateSpec(config);
    message.warning('Swagger YAML 已重置。');
  }

  save() {
    const { dispatch } = this.props;
    const config = this.editor.specSelectors.specStr();
    const callback = () => {
        message.success('Swagger YAML 已保存。');
    };
    dispatch({
        type: 'swaggerConfig/update',
        payload: { config, callback },
    });
  }

  render() {
    return (
        <>
            <div id="swagger-editor" className={styles.editor}></div>
            <div style={{ padding: '16px', backgroundColor: 'white', }}>
                <Button type="primary" onClick={this.save.bind(this)}>保存</Button> &nbsp;&nbsp;
                <Button type="danger" onClick={this.reset.bind(this)}>重置</Button>
            </div>
        </>
    );
  }
}

export default SwaggerEditorPage;
